/**
 * Jul 1, 2014 2:46:32 PM
 */
package elitech.vietnam.myfashion.extend;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.wsclient.Service;

/**
 * @author Cong
 *
 */
public class MenuSearchAutoCompleteAdapter extends ArrayAdapter<Product> implements Filterable {

	MainActivity mActivity;
	/**
	 * @param context
	 * @param resource
	 * @param objects
	 */
	public MenuSearchAutoCompleteAdapter(Context context, int resource, List<Product> objects) {
		super(context, resource, objects);
		mActivity = (MainActivity) context;
	}

	@Override
	public int getCount() {
		return mActivity.mListSearch.size();
	}
	
	@Override
	public Product getItem(int position) {
		return mActivity.mListSearch.get(position);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
		}
		((TextView) convertView).setText(getItem(position).Name);
		return convertView;
	}
	
	@Override
	public Filter getFilter() {
		return new Filter() {
			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				Log.w(getClass().getSimpleName(), "publishResults");
				mActivity.mListSearch.clear();
				if (results.count > 0) {
					mActivity.mListSearch.addAll((ArrayList<Product>) results.values);
				}
				notifyDataSetChanged();
			}
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				Log.w(getClass().getSimpleName(), "performFiltering");
				FilterResults result = new FilterResults();
				List<Product> list = null;
				try {
					if (constraint != null) {
						int n = (mActivity.mUser != null) ? mActivity.mUser.Id : -1;
						list = new Service().searchProduct(constraint.toString(), n);
					}
				} catch (IOException | XmlPullParserException e) {
					e.printStackTrace();
				}
				list = (list == null) ? new ArrayList<Product>() : list;
				result.values = list;
				result.count = list.size();
				return result;
			}
		};
	}
	
}
